﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Odyssey.Linq;
using SunTzu.Core.Data;
using log4net;
using System.Reflection;

namespace Odyssey.Web.Models
{
    public static class CacheHelper<T> where T : class, IEntity, new()
    {
        private static ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private static OdysseyDataContext db
        {
            get
            {
                return DataContextManager.GetContext();
            }
        }

        private static List<T> cachedList = null;
        private static Dictionary<int, T> cachedDictionary = null;

        public static List<T> GetAll()
        {
            if (cachedList == null)
            {
                logger.DebugFormat("加载缓存数据。类型：{0}", typeof(T).Name);
                cachedList = db.GetTable<T>().ToList();
                cachedDictionary = cachedList.ToDictionary(c => c.Id);
                logger.DebugFormat("加载缓存数据完毕。类型：{0}， 共{1}条", typeof(T).Name, cachedList.Count);
            }
            return cachedList;
        }

        public static void Clear()
        {
            logger.DebugFormat("清空缓存数据。类型：{0}", typeof(T).Name);
            cachedList = null;
            cachedDictionary = null;
        }

        public static T GetById(int id)
        {
            if (cachedDictionary == null)
            {
                GetAll();
            }
            if (cachedDictionary.ContainsKey(id))
            {
                return cachedDictionary[id];
            }
            return new T();
        }
    }
}